package normal.哈希表.基于列表实现;

import java.util.ArrayList;
import java.util.List;

import static java.util.Objects.hash;

/**
 * 基于集合实现的哈希表
 *
 * @author ZhuYi
 * @create 2025/1/16 23:13
 */
public class ListHash {
    private List<Pair> buckets;

    public ListHash() {
        buckets = new ArrayList<>();
        //初始化列表，包含100个桶
        for (int i = 0; i < 100; i++) {
            buckets.add(null);
        }
    }


    //哈希计算
    private int hashFunc(int key) {
        int index = hash(key) % 100;
        return index;
    }

    //查询
    public String get(int key) {
        int index = hashFunc(key);
        Pair pair = buckets.get(index);
        return pair.val;
    }

    //添加
    public void put(int key, String val) {
        Pair pair = new Pair(key, val);
        int index = hashFunc(key);
        buckets.set(index, pair);
    }

    //删除
    public void remove(int key) {
        int index = hashFunc(key);
        // 置为 null ，代表删除
        buckets.set(index, null);
    }

    //获取所有键值对
    public List<Pair> getBuckets() {
        List<Pair> list = new ArrayList<>();
        for (Pair p : buckets) {
            if (p != null) {
                list.add(p);
            }
        }
        return list;
    }

    // 获取所有键
    public List<Integer> getKeys() {
        List<Integer> list = new ArrayList<>();
        for (Pair p : buckets) {
            if (p != null) {
                list.add(p.key);
            }
        }
        return list;
    }

    // 获取所有键
    public List<String> getValues() {
        List<String> list = new ArrayList<>();
        for (Pair p : buckets) {
            if (p != null) {
                list.add(p.val);
            }
        }
        return list;
    }

    //打印哈希表
    public void print() {
        for (Pair p : buckets) {
            if (p != null) {
                System.out.println(p.key + " = " + p.val);
            }
        }
    }
}
